//
//  ViewController.m
//  UILabelDemoes
//
//  Created by 红沙尘 on 2018/11/25.
//  Copyright © 2018年 红沙尘. All rights reserved.
//

#import "ViewController.h"
#import "HSCLabel.h"

@interface ViewController () {
    UIView *flagView;//遮罩框
    NSInteger tag;//记录点击tag
}

@property (weak, nonatomic) IBOutlet HSCLabel *label;
@property (strong, nonatomic) NSTextStorage *textStorage;
@property (strong, nonatomic) NSLayoutManager *layoutManager;
@property (strong, nonatomic) NSTextContainer *textContainer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.textStorage = [NSTextStorage new];
//    self.layoutManager = [NSLayoutManager new];
//    self.textContainer = [NSTextContainer new];
//    
//    [self.layoutManager addTextContainer:self.textContainer];
//    [self.textStorage addLayoutManager:self.layoutManager];
//    
//    
//    tag = 0;
//    
//    [_label sizeToFit];
//    
//    flagView = [UIView new];
//    flagView.frame = CGRectZero;
//    flagView.layer.borderColor = [UIColor redColor].CGColor;
//    flagView.layer.borderWidth = 1.f;
//    flagView.clipsToBounds = YES;
//    
//    [self.label addSubview:flagView];
}

- (IBAction)buttonAction:(id)sender {
    [self.label rectAtIndex:self.label.text.length - 1];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self configWithLabel:self.label];
}

- (void)configWithLabel:(UILabel *)label {
    self.textContainer.size = label.bounds.size;
    self.textContainer.lineFragmentPadding = 0;
    self.textContainer.maximumNumberOfLines = label.numberOfLines;
    self.textContainer.lineBreakMode = label.lineBreakMode;
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:label.text];
    
    NSRange textRange = NSMakeRange(0, attributedText.length);
    [attributedText addAttribute:NSFontAttributeName value:label.font range:textRange];
    
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.alignment = label.textAlignment;
    [attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:textRange];
    
    [self.textStorage setAttributedString:attributedText];
}

- (CGRect)characterRectAtIndex:(NSUInteger)charIndex {
    //传回self.layoutManager的位置 实际就是字符的fram
    if (charIndex >= self.textStorage.length) {
        return CGRectZero;
    }
    
    NSRange characterRange = NSMakeRange(charIndex, 1);
    
    NSRange glyphRange = [self.layoutManager glyphRangeForCharacterRange:characterRange actualCharacterRange:nil];
    
    return [self.layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:self.textContainer];
}


@end
